package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartInfoFeignClient;
import com.atguigu.gmall.client.UserFeignClient;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author gsy
 * @date 2021年09月10日19:27
 * Description
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartInfoFeignClient cartInfoFeignClient;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedisTemplate redisTemplate;


    //查询订单页面所需要的数据
    @GetMapping("/auth/trade")
    public Map trade(HttpServletRequest request) {
        //用户id
        String userId = AuthContextHolder.getUserId(request);
        Map map = new HashMap();
        //获取用户地址集合
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        map.put("userAddressList", userAddressList);
        //获取商品清单
        List<CartInfo> cartInfoList = cartInfoFeignClient.getCartCheckedList(userId);
        //将购物车集合转化成订单集合(页面需要)
        List<OrderDetail> orderDetailList = cartInfoList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cartInfo, orderDetail);
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            return orderDetail;
        }).collect(Collectors.toList());
        map.put("detailArrayList", orderDetailList);
        //总数量  totalNum
        long totalNum = orderDetailList.stream().collect(Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        map.put("totalNum", totalNum);
        //总金额 totalAmount
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail orderDetail : orderDetailList) {
            totalAmount = totalAmount.add(orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum())));
        }
        map.put("totalAmount", totalAmount);
        //生成订单号防止重复提交(幂等性问题) tradeNo
        String tradeNo = UUID.randomUUID().toString();
        //存入缓存
        redisTemplate.opsForValue().set("trade:" + userId, tradeNo);
        map.put("tradeNo", tradeNo);

        return map;
    }

    @PostMapping("/auth/submitOrder")
    public Result submitOrder(String tradeNo, @RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //校验交易号
        Object o = redisTemplate.opsForValue().get("trade:" + userId);
        if (o != null && o.equals(tradeNo)) {
            //交易号校验成功
            redisTemplate.delete("trade:" + userId);

            //查询库存够不够
            List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
            for (OrderDetail orderDetail : orderDetailList) {
                boolean flag = orderInfoService.hasStock(orderDetail);
                if (!flag) {

                    return Result.fail().message(orderDetail.getSkuName() + "[库存不足]");
                }
            }
            // 保存订单
            //用户id
            orderInfo.setUserId(Long.parseLong(userId));
            Long orderId = orderInfoService.saveOrderInfo(orderInfo);
            return Result.ok(orderId);


        }

        return Result.fail().message("不能重复提交订单");

    }
    //查询订单金额及其相关信息
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable  Long orderId){
       return orderInfoService.getOrderInfo(orderId);


    }
    //拆单 http://order.gmall.com/orderSplit  orderId  wareSkuMap
    @GetMapping("/orderSplit")
    public List<Map> orderSplit(Long orderId,String wareSkuMap){
       List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
       orderInfoList.stream().map(orderInfo -> {
           Map map = orderInfoService.initWareOrder(orderInfo);
           return map;
       }).collect(Collectors.toList());
       return null;

    }
}
